<!--
  ~
  ~  Copyright (c) 2018-2025, Pactera JinXin Software All rights reserved.
  ~
  -->

<template>
    <div class="app-container calendar-list-container">
        <basic-container>
            <div>
                <el-button type="primary" @click="handleCreate">添加</el-button>
            </div>
            <el-table
                :header-cell-style="{
                    background: 'rgb(255, 191, 191)',
                    color: 'rgb(44,44,44)'
                }"
                :data="list"
                style="width: 100%;margin:20px 0"
                v-loading="listLoading"
            >
                <el-table-column label="序号" type="index" width="70">
                    <template slot-scope="scope">{{ (page.currentPage - 1) * page.pageSize + scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色标志" prop="roleCode"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <!-- <el-table-column label="数据权限" prop="dsType">
                    <template slot-scope="scope">{{dsType[scope.row.dsType]}}</template>
                </el-table-column>-->
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleView(scope.row)">查看</el-button>
                        <el-button v-if="scope.row.roleCode != 'ROLE_ADMIN'" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button v-if="scope.row.roleCode != 'ROLE_ADMIN'" type="text" @click="handleDelete(scope.row)">删除</el-button>
                        <el-button v-if="scope.row.roleCode != 'ROLE_ADMIN'" type="text" @click="handlePermission(scope.row)">权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                background
                class="madp-pagination"
                @size-change="handlePageSize"
                @current-change="handlePageCurrent"
                :current-page="page.currentPage"
                :page-sizes="[10, 20, 30, 50, 100]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
            ></el-pagination>
        </basic-container>
        <el-dialog :visible.sync="dialogPermissionVisible" :close-on-click-modal="false" title="分配权限">
            <div class="dialog-main-tree">
                <el-tree
                    ref="menuTree"
                    :data="treeData"
                    :default-checked-keys="checkedKeys"
                    :check-strictly="false"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    class="filter-tree"
                    node-key="id"
                    highlight-current
                    show-checkbox
                    default-expand-all
                />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="updatePermession(roleId)">更新</el-button>
                <el-button type="default" @click="cancal()">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogShow" :close-on-click-modal="false" :title="dialogTitle">
            <el-form :model="form" :rules="rules" ref="form" :disabled="isDisabled" label-width="100px" v-if="dialogShow">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model.trim="form.roleName" placeholder="请输入角色名称" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="角色标识" prop="roleCode">
                    <el-input v-model.trim="form.roleCode" placeholder="角色标识" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input type="textarea" v-model="form.roleDesc" maxlength="200" :placeholder="dialogTitle == '查看角色' ? '' : '请输入角色描述'"></el-input>
                </el-form-item>
                <!-- <el-form-item label="数据权限" prop="dsType">
                    <el-select v-model.trim="form.dsType">
                        <el-option :value="0" label="全部"></el-option>
                        <el-option :value="1" label="自定义"></el-option>
                        <el-option :value="2" label="本级及子级"></el-option>
                        <el-option :value="3" label="本级"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="form.dsType == 1">
                    <el-tree
                        ref="scopeTree"
                        :data="dsScopeData"
                        :check-strictly="true"
                        :props="defaultProps"
                        :default-checked-keys="checkedDsScope"
                        class="filter-tree"
                        node-key="id"
                        highlight-current
                        show-checkbox
                    />
                </el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button v-show="dialogTitle != '查看角色'" type="primary" @click="handleSumbit">{{ dialogTitle == '新增角色' ? '提交' : dialogTitle == '编辑角色' ? '保存' : '确定' }}</el-button>
                <el-button :type="dialogTitle == '查看角色' ? 'primary' : 'default'" @click="cancal()">{{ dialogTitle == '查看角色' ? '确定' : '取消' }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { rule } from '@/util/validate-rules';
import { addObj, delObj, fetchList, fetchRoleTree, permissionUpd, putObj } from '@/api/admin/role';
import { fetchTree } from '@/api/admin/dept';
import { fetchMenuTree } from '@/api/admin/menu';
import { mapGetters } from 'vuex';

export default {
    name: 'TableRole',
    data() {
        return {
            // 权限类型
            dsType: ['全部', '自定义', '本级及子级', '本级'],
            dialogShow: false, // 弹窗开关
            dialogTitle: '', // 弹窗标题
            searchForm: {}, // 查询表单
            dsScopeData: [],
            treeData: [], // 表格数据
            checkedKeys: [], // 已选中节点
            checkedDsScope: [],
            defaultProps: {
                label: 'name',
                value: 'id'
            },
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 20 // 每页显示多少条
            },
            menuIds: '', // 节点id
            list: [], // 表格数据
            listLoading: true, //表格loading开关
            form: {}, // 表单对象
            roleId: undefined, // 角色id
            roleCode: undefined, // 角色标志
            rolesOptions: undefined, // 角色选择项
            dialogPermissionVisible: false,
            // 按钮权限
            roleManager_btn_add: false,
            roleManager_btn_edit: false,
            roleManager_btn_del: false,
            roleManager_btn_perm: false,
            // 表单校验规则
            rules: {
                roleName: [
                    {
                        required: true,
                        message: '角色名称不能为空',
                        trigger: 'blur'
                    },
                    {
                        required: true,
                        min: 3,
                        max: 20,
                        message: '长度在 3 到 20 个字符',
                        trigger: 'blur'
                    }
                ],
                roleCode: [
                    {
                        required: true,
                        message: '角色标识不能为空',
                        trigger: 'blur'
                    },
                    {
                        required: true,
                        min: 3,
                        max: 20,
                        message: '长度在 3 到 20 个字符',
                        trigger: 'blur'
                    },
                    {
                        required: true,
                        validator: rule.validatorKey,
                        trigger: 'blur'
                    }
                ]
                // dsType: [
                //     {
                //         required: true,
                //         message: "请选择数据权限类型",
                //         trigger: "change"
                //     }
                // ]
            },
            form: {}, // 表单对象
            isDisabled: false // 是否禁止编辑
        };
    },
    created() {
        this.roleManager_btn_add = this.permissions['sys_role_add'];
        this.roleManager_btn_edit = this.permissions['sys_role_edit'];
        this.roleManager_btn_del = this.permissions['sys_role_del'];
        this.roleManager_btn_perm = this.permissions['sys_role_perm'];
        this.getList();
    },
    computed: {
        ...mapGetters(['elements', 'permissions'])
    },
    methods: {
        // 改变分页大小
        handlePageSize(val) {
            this.page.pageSize = val;
            this.getList(1);
        },
        // 改变分页页码
        handlePageCurrent(val) {
            this.page.currentPage = val;
            this.getList(1);
        },
        // 获取表格数据
        getList(data) {
            if (!data) {
                this.page.currentPage = 1;
                this.page.pageSize = 10;
            }
            let obj = {
                current: this.page.currentPage,
                size: this.page.pageSize
            };
            this.listLoading = true;
            fetchList(obj)
                .then((response) => {
                    this.list = response.data.data.records;
                    this.page.total = response.data.data.total;
                    this.listLoading = false;
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        // 点击刷新
        handleRefreshChange() {
            this.getList(this.page);
        },
        // 条件查询
        handleFilter(form) {
            this.searchForm = form;
            this.getList(this.page, form);
        },
        // 点击新增
        handleCreate() {
            this.isDisabled = false;
            this.dialogShow = true;
            this.dialogTitle = '新建角色';
            this.form = {
                roleName: '',
                roleCode: '',
                roleDesc: ''
                // dsType: 0
            };
            this.handleOpenBefore();
        },
        // 在打开之前执行函数
        handleOpenBefore() {
            fetchTree().then((response) => {
                this.dsScopeData = response.data.data;
                if (this.form.dsScope) {
                    this.checkedDsScope = this.form.dsScope.split(',');
                } else {
                    this.checkedDsScope = [];
                }
            });
        },
        // 点击查看
        handleView(row) {
            this.isDisabled = true;
            this.dialogShow = true;
            this.dialogTitle = '查看角色';
            this.form = row;
        },
        // 点击编辑
        handleUpdate(row) {
            this.isDisabled = false;
            this.dialogShow = true;
            this.dialogTitle = '编辑角色';
            this.form = JSON.parse(JSON.stringify(row));
            this.handleOpenBefore();
        },
        // 点击取消
        cancal() {
            this.dialogPermissionVisible = false;
            this.dialogShow = false;
            this.form = {};
        },
        // 点击权限
        handlePermission(row) {
            fetchRoleTree(row.roleId)
                .then((response) => {
                    this.checkedKeys = response.data.data;
                    return fetchMenuTree();
                })
                .then((response) => {
                    this.treeData = response.data.data;
                    // 解析出所有的太监节点
                    this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeys, []);
                    this.dialogPermissionVisible = true;
                    this.roleId = row.roleId;
                    this.roleCode = row.roleCode;
                });
        },
        /**
         * 解析出所有的太监节点id
         * @param json 待解析的json串
         * @param idArr 原始节点数组
         * @param temp 临时存放节点id的数组
         * @return 太监节点id数组
         */
        resolveAllEunuchNodeId(json, idArr, temp) {
            for (let i = 0; i < json.length; i++) {
                const item = json[i];
                // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
                if (item.children && item.children.length !== 0) {
                    this.resolveAllEunuchNodeId(item.children, idArr, temp);
                } else {
                    temp.push(idArr.filter((id) => id === item.id));
                }
            }
            return temp;
        },
        // 节点过滤
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 点击删除
        handleDelete(row) {
            this.$confirm("是否确认删除名称为'" + row.roleName + "'" + '的数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(function() {
                    return delObj(row.roleId);
                })
                .then(() => {
                    if (this.list.length === 1 && this.page.currentPage > 1) this.page.currentPage -= 1;
                    this.getList(this.page);
                    this.$notify.success('删除成功');
                })
                .catch(() => {});
        },
        // 新增确定
        create(row, done, loading) {
            // if (this.form.dsType === 1) {
            //     this.form.dsScope = this.$refs.scopeTree
            //         .getCheckedKeys()
            //         .join(",");
            // }
            addObj(this.form)
                .then(() => {
                    this.getList(this.page);
                    done();
                    this.$notify.success('创建成功');
                })
                .catch(() => {
                    loading();
                });
        },
        // 更新权限
        updatePermession(roleId) {
            this.menuIds = '';
            this.menuIds = this.$refs.menuTree
                .getCheckedKeys()
                .join(',')
                .concat(',')
                .concat(this.$refs.menuTree.getHalfCheckedKeys().join(','));
            permissionUpd(roleId, this.menuIds).then(() => {
                this.dialogPermissionVisible = false;
                this.$store.dispatch('GetMenu', { type: false });
                this.$notify.success('修改成功');
            });
        },
        // 点击确定
        handleSumbit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    // if (this.form.dsType === 1) {
                    //     this.form.dsScope = this.$refs.scopeTree
                    //         .getCheckedKeys()
                    //         .join(",");
                    // }
                    if (this.dialogTitle == '新建角色') {
                        addObj(this.form)
                            .then(() => {
                                this.dialogShow = false;
                                this.getList(1);
                                this.$notify.success('创建成功');
                            })
                            .catch(() => {});
                    } else {
                        putObj(this.form).then(() => {
                            this.dialogShow = false;
                            this.getList(1);
                            this.$notify.success('修改成功');
                        });
                    }
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
    .el-dialog {
        width: 61% !important;
        .dialog-main-tree {
            max-height: 400px;
            overflow-y: auto;
        }
    }
    .el-form-item__label {
        width: 20% !important;
        padding-right: 20px;
    }
    .el-form-item__content {
        margin-left: 20% !important;
    }
}
</style>
